﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

using GPTAS.Infrastructure;
using GPTAS.Database;

namespace GPTAS.Core
{
    public class Allocator
    {

        private readonly static Allocator _instance = new Allocator();

        private Allocator()
        {
            Allocations = new Dictionary<int, Allocation>();
            IteminGroup = new Dictionary<int, int>();
        }

        public static Allocator Instance
        {
            get { return _instance; }
        }

        public Dictionary<int, int> IteminGroup
        {
            get;
            set;
        }

        public int CurrentAllocationId
        {
            get;
            set;
        }

        public Dictionary<int, Allocation> Allocations
        {
            get;
            set;
        }

        private Dictionary<int, Group> Allocate()
        {
            return null;
        }

        public void GetAllocations()
        {
            DataTable dt = Database.Database.Instance.GetAllocations();
            if (dt != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    int allocationid = Convert.ToInt32(dt.Rows[i].ItemArray[0].ToString());
                    string allocationname = dt.Rows[i].ItemArray[1].ToString();
                    Allocation a=new Allocation(allocationname, allocationid);
                    Allocations.Add(a.Id, a);
                    a.GetItems();
                    a.GetGroups();
                    a.GetItemsForGroups();
                }
            }            
        }

        public void AddAllocation(string allocationname)
        {
            int allocationid = Database.Database.Instance.NewAllocation(allocationname);
            if (allocationid > 0)
            {
                Allocations.Add(allocationid, new Allocation(allocationname, allocationid));
                CurrentAllocationId = allocationid;
            }            
        }

        public void AddGroup(string groupname)
        {
            int groupid = Database.Database.Instance.NewGroup(CurrentAllocationId,groupname);
            if (groupid > 0)
            {
                Group g=new Group(groupid,groupname);
                Allocation a=new Allocation();
                if (Allocations.TryGetValue(CurrentAllocationId, out a))
                {
                    a.Groups.Add(groupid, g);
                }
            }
        }

    }
}
